package com.program.facesigninsystem.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Mapler
 */
public class ScanCodeUtil {
    private static Logger log = Logger.getLogger(ScanCodeUtil.class.toString());
    final private static String SIGN = "www.xqzjgsu.xyz";

    public static Map<String,String> encodeCode(String lid){
        Map<String,String> map = new HashMap<>(1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = dateFormat.format(System.currentTimeMillis()+12000);
        map.put("code",JWT.create().withClaim("lid",lid).withClaim("endTime",endTime).sign(Algorithm.HMAC256(SIGN)));
        return map;
    }

    public static String decodeCode(String code){
        DecodedJWT decodedJwt;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            decodedJwt = JWT.decode(code);
            String endTime = decodedJwt.getClaim("endTime").asString();
            long time = simpleDateFormat.parse(endTime).getTime();
            long currentTime = System.currentTimeMillis();
            if (currentTime > time) {
                return "CodeExpired";
            }
        }catch (ParseException e){
            log.log(Level.SEVERE,"Error parsing date",e);
            return "InvalidCode";
        }catch (IllegalArgumentException e){
            log.log(Level.SEVERE,"Error decode code",e);
            return "InvalidCode";
        }
        return decodedJwt.getClaim("lid").asString();
    }
}
